package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("HazardRestController")
public class HazardRestController extends CmiEmaController {

	/**
	 * Create a new Hazard entity
	 * 
	 */
	@RequestMapping(value = "/newHazard", method = RequestMethod.POST)
	@ResponseBody
	public Object newHazard(@RequestBody Hazard hazard) {
		hazardService.saveHazard(hazard);
		return JSONObject.parse(cmiPsonService.toJsonString(hazardDAO.findHazardByPrimaryKey(hazard.getId()), 2));
	}

	@RequestMapping(value = "/restNewHazard", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewHazard(@RequestBody String hazardJson) {
		Hazard hazard = new Gson().fromJson(hazardJson, Hazard.class);
		appendReferences(hazard);
		hazardService.saveHazard(hazard);
		return JSONObject.parse(cmiPsonService.toJsonString(hazardDAO.findHazardByPrimaryKey(hazard.getId()), 2));
	}

	@RequestMapping(value = "/saveHazard", method = RequestMethod.PUT)
	@ResponseBody
	public Hazard saveHazard(@RequestBody Hazard hazard) {
		hazardService.saveHazard(hazard);
		return hazardDAO.findHazardByPrimaryKey(hazard.getId());
	}

	@RequestMapping(value = "/restSaveHazard", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveHazard(@RequestBody String hazardJson) {
		Hazard hazard = new Gson().fromJson(hazardJson, Hazard.class);
		appendReferences(hazard);
		CmiPsonService cmiPsonService = new CmiPsonService();
		hazardService.saveHazard(hazard);
		return JSONObject.parse(cmiPsonService.toJsonString(hazardDAO.findHazardByPrimaryKey(hazard.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteHazard/{hazardId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteHazard(@PathVariable Integer hazardId) {
		Hazard hazard = hazardDAO.findHazardByPrimaryKey(hazardId);
		hazardService.deleteHazard(hazard);
	}

	@RequestMapping(value = "/restConfirmDeleteHazards")
	@ResponseBody
	public Object restConfirmDeleteHazards(@RequestBody Set<Integer> deleteHazardsIds) {
		Set<Hazard> deleteHazards = hazardDAO.findHazardsByIds(deleteHazardsIds);
		Set<Hazard> referencedHazards = hazardService.loadReferenceHazards(deleteHazards);
		deleteHazards.removeAll(referencedHazards);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedHazards);
		jsonObject.put("deleteEntitys", deleteHazards);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteHazards")
	@ResponseBody
	public Object restDeleteHazards(@RequestBody Set<Hazard> deleteHazards) {
		Iterator<Hazard> iterator = deleteHazards.iterator();
		while (iterator.hasNext()) {
			Hazard currentHazard = iterator.next();
			hazardService.deleteHazard(currentHazard);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listHazards");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadHazard/{hazardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadHazard(@PathVariable Integer hazardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(hazardDAO.findHazardByPrimaryKey(hazardId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadHazardEventhazards/{hazardId}/eventhazards/{relatedeventhazardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadHazardEventhazards(@PathVariable Integer hazardId, @PathVariable Integer relatedeventhazardId,
			@RequestBody CmiPagination cmiPagination) {
		Eventhazard eventhazard = eventhazardDAO.findEventhazardByPrimaryKey(relatedeventhazardId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventhazard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadHazardFillerhazards/{hazardId}/fillerhazards/{relatedfillerhazardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadHazardFillerhazards(@PathVariable Integer hazardId,
			@PathVariable Integer relatedfillerhazardId, @RequestBody CmiPagination cmiPagination) {
		Fillerhazard fillerhazard = fillerhazardDAO.findFillerhazardByPrimaryKey(relatedfillerhazardId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(fillerhazard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadHazardFillertypes/{hazardId}/fillertypes/{relatedfillertypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadHazardFillertypes(@PathVariable Integer hazardId, @PathVariable Integer relatedfillertypeId,
			@RequestBody CmiPagination cmiPagination) {
		Fillertype fillertype = fillertypeDAO.findFillertypeByPrimaryKey(relatedfillertypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(fillertype, 2, cmiPagination));
	}

	public void appendReferences(Hazard hazard) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventhazard> eventhazardsForHazard = new HashSet<>();
		for (Eventhazard eventhazard_Hazard : hazard.getEventhazardsForHazard()) {
			eventhazardsForHazard.add(eventhazardService.findEventhazardByPrimaryKey(eventhazard_Hazard.getId()));
		}
		hazard.setEventhazardsForHazard(eventhazardsForHazard);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Fillerhazard> fillerhazardsForHazard = new HashSet<>();
		for (Fillerhazard fillerhazard_Hazard : hazard.getFillerhazardsForHazard()) {
			fillerhazardsForHazard.add(fillerhazardService.findFillerhazardByPrimaryKey(fillerhazard_Hazard.getId()));
		}
		hazard.setFillerhazardsForHazard(fillerhazardsForHazard);

		// 引用表是纯联系表的情况
		Set<Fillertype> fillertypesForHazard = new HashSet<>();
		for (Fillertype fillertypeForHazard : hazard.getFillertypesForHazard()) {
			fillertypesForHazard.add(fillertypeService.findFillertypeByPrimaryKey(fillertypeForHazard.getId()));
		}
		hazard.setFillertypesForHazard(fillertypesForHazard);
	}

	@RequestMapping(value = "/restGetHazardEventhazards/{hazardId}/eventhazards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetHazardEventhazards(@PathVariable Integer hazardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(hazardDAO.findHazardByPrimaryKey(hazardId).getEventhazardsForHazard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetHazardFillerhazards/{hazardId}/fillerhazards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetHazardFillerhazards(@PathVariable Integer hazardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(hazardDAO.findHazardByPrimaryKey(hazardId).getFillerhazardsForHazard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetHazardFillertypes/{hazardId}/fillertypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetHazardFillertypes(@PathVariable Integer hazardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(hazardDAO.findHazardByPrimaryKey(hazardId).getFillertypesForHazard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListHazards", method = RequestMethod.GET)
	@ResponseBody
	public Object restListHazards() {
		return JSONObject.parse(cmiPsonService.toJsonString(hazardService.loadHazards(), 2));
	}

	@RequestMapping(value = "/restListHazardsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListHazardsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = hazardPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Hazard> hazards = hazardDAO.findAllHazards(startResult, cmiPagination.getPaginationSize());
		String hazardString = cmiPsonService.toPsonString(hazards, 2, cmiPagination);

		return JSONObject.parse(hazardString);
	}

	@RequestMapping("/hazardSelectBox")
	@ResponseBody
	public JSONObject hazardSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Eventhazard":
				entitySet = eventhazardService.loadEventhazardsByIdSet(searchValue);
				break;
			case "Fillerhazard":
				entitySet = fillerhazardService.loadFillerhazardsByIdSet(searchValue);
				break;

			case "Fillertype":
				entitySet = fillertypeService.loadFillertypesByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Eventhazard":
				entitySet = eventhazardDAO.findAllEventhazards((pageNumber - 1) * paginationSize, paginationSize);
				count = eventhazardService.countEventhazards();
				break;
			case "Fillerhazard":
				entitySet = fillerhazardDAO.findAllFillerhazards((pageNumber - 1) * paginationSize, paginationSize);
				count = fillerhazardService.countFillerhazards();
				break;

			case "Fillertype":
				entitySet = fillertypeDAO.findAllFillertypes((pageNumber - 1) * paginationSize, paginationSize);
				count = fillertypeService.countFillertypes();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Eventhazard":
				entitySet = eventhazardDAO.findEventhazardByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventhazardService.countEventhazardsByName(queryword);
				break;
			case "Fillerhazard":
				entitySet = fillerhazardDAO.findFillerhazardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = fillerhazardService.countFillerhazardsByName(queryword);
				break;

			case "Fillertype":
				entitySet = fillertypeDAO.findFillertypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = fillertypeService.countFillertypesByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
